<template>
  <div class="search-page">
    <div class="search-header">
      <div class="search-top">
        <div class="back-button" @click="router.go(-1)">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回</span>
        </div>
        <h1 class="search-title">搜索结果</h1>
      </div>
      <div class="search-bar-container">
        <SearchBar :initialKeyword="keyword" />
      </div>
    </div>
    
    <div class="search-content">
      <!-- 添加高级搜索区域 -->
      <div class="advanced-search" v-if="showAdvancedSearch">
        <AdvancedSearchForm 
          :keyword="keyword"
          :initial-values="advancedSearchForm"
          @search="doAdvancedSearch"
          @close="showAdvancedSearch = false"
        />
      </div>

      <!-- 添加搜索建议和相关标签区域 -->
      <div class="search-meta" v-if="keyword && (searchSuggestions.length > 0 || relatedTags.length > 0)">
        <!-- 搜索建议 -->
        <div class="search-suggestions" v-if="searchSuggestions.length > 0">
          <h3 class="suggestions-title">搜索建议</h3>
          <div class="suggestions-list">
            <div 
              v-for="(suggestion, index) in searchSuggestions" 
              :key="index"
              class="suggestion-item"
              @click="selectSuggestion(suggestion)"
            >
              {{ suggestion }}
            </div>
          </div>
        </div>
        
        <!-- 相关标签 -->
        <div class="related-tags" v-if="relatedTags.length > 0">
          <h3 class="tags-title">相关标签</h3>
          <div class="tags-list">
            <el-tag
              v-for="(tag, index) in relatedTags"
              :key="index"
              class="tag-item"
              @click="selectRelatedTag(tag)"
              effect="light"
              size="small"
              :title="`点击搜索: ${tag}`"
            >
              {{ tag }}
              <span class="tag-usage-count" v-if="tagUsageCounts[tag]">
                ({{ tagUsageCounts[tag] }})
              </span>
            </el-tag>
          </div>
          <div class="tags-hint" v-if="relatedTags.length > 0">
            <el-icon><InfoFilled /></el-icon>
            <span>点击标签可快速筛选相关内容</span>
          </div>
        </div>
      </div>
      
      <div class="search-tabs">
        <div class="search-operations">
          <el-button v-if="!showAdvancedSearch" type="primary" text @click="showAdvancedSearch = true">
            <el-icon><Setting /></el-icon> 高级搜索
          </el-button>
          <el-tooltip content="查看搜索使用技巧" placement="top">
            <el-button type="info" text @click="openSearchTips">
              <el-icon><QuestionFilled /></el-icon> 搜索指南
            </el-button>
          </el-tooltip>
          <el-radio-group v-model="simpleSort" size="small" @change="handleSimpleSortChange" v-if="!showAdvancedSearch">
            <el-radio-button :label="1">相关度</el-radio-button>
            <el-radio-button :label="2">最新</el-radio-button>
            <el-radio-button :label="3">最热</el-radio-button>
          </el-radio-group>
        </div>
        
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="问题" name="questions">
            <div class="tab-content">
              <!-- 问题搜索结果 -->
              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
              </div>
              
              <div v-else-if="questionResults.length === 0" class="empty-results">
                <el-empty 
                  description="未找到相关问题" 
                  :image-size="200"
                >
                  <template #description>
                    <p>未找到与"{{ keyword }}"相关的问题</p>
                    <p v-if="!loading">您可以尝试其他关键词或者去提问</p>
                  </template>
                  <el-button type="primary" @click="router.push('/ask')">去提问</el-button>
                </el-empty>
              </div>
              
              <div v-else class="search-results">
                <div class="result-summary">
                  找到 {{ questionTotal }} 个与"{{ keyword }}"相关的问题
                </div>
                
                <div class="question-list">
                  <div
                    v-for="question in questionResults"
                    :key="question.id"
                    class="question-card"
                    @click="viewQuestionDetail(question.id)"
                  >
                    <!-- 问题卡片头部（用户信息） -->
                    <div class="question-card-header">
                      <el-avatar :size="36" :src="question.user?.avatar || question.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"></el-avatar>
                      <div class="user-info">
                        <div class="username">{{ question.user?.username || question.username || question.nickname || '未知用户' }}</div>
                        <div class="publish-time">发布于 {{ formatTime(question.createTime || question.created_at) }} · 浏览 {{ question.viewCount || question.views_count || 0 }}</div>
                      </div>
                    </div>
                    
                    <!-- 问题标题和内容预览 -->
                    <div class="question-content">
                      <h3 class="question-title" v-html="highlightKeyword(question.title)"></h3>
                      <p class="question-preview" v-html="highlightKeyword(question.contentPreview || question.content)"></p>
                      <div class="tags" v-if="getQuestionTags(question).length > 0">
                        <el-tag
                          v-for="tag in getQuestionTags(question)"
                          :key="tag"
                          size="small"
                          effect="plain"
                          class="tag-item"
                          v-html="question.highlightFields && question.highlightFields.tags ? highlightKeyword(tag) : tag"
                        >
                        </el-tag>
                      </div>
                    </div>
                    
                    <!-- 问题标签和统计 -->
                    <div class="question-footer">
                      <div class="interaction-area">
                        <!-- 投票区域 -->
                        <div class="vote-area">
                          <el-button 
                            class="vote-btn" 
                            type="text"
                            :class="{'active-vote': question.voteStatus === 1}"
                            @click.stop="isLogin ? handleVote(question.id, 'up') : router.push('/login')"
                          >
                            <el-icon><CaretTop /></el-icon>
                          </el-button>
                          <span class="vote-count" :class="{'voted-up': question.voteStatus === 1, 'voted-down': question.voteStatus === 2}">
                            {{ question.voteCount || question.votes_count || 0 }}
                          </span>
                          <el-button 
                            class="vote-btn" 
                            type="text"
                            :class="{'active-vote-down': question.voteStatus === 2}"
                            @click.stop="isLogin ? handleVote(question.id, 'down') : router.push('/login')"
                          >
                            <el-icon><CaretBottom /></el-icon>
                          </el-button>
                        </div>

                        <!-- 回答数量 -->
                        <div class="answer-count">
                          <el-icon><ChatLineSquare /></el-icon>
                          <span>{{ question.answerCount || question.answers_count || 0 }}条回答</span>
                        </div>

                        <!-- 收藏 -->
                        <el-button 
                          type="text" 
                          class="action-btn" 
                          :class="{'is-collected': question.isBookmarked || question.is_bookmarked}"
                          @click.stop="isLogin ? handleBookmark(question.id) : router.push('/login')"
                        >
                          <el-icon :class="{'active-icon': question.isBookmarked || question.is_bookmarked}">
                            <Star />
                          </el-icon>
                          <span :class="{'active-text': question.isBookmarked || question.is_bookmarked}">
                            {{ (question.isBookmarked || question.is_bookmarked) ? '已收藏' : '收藏' }}
                          </span>
                        </el-button>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 加载更多 -->
                  <div class="load-more-container" v-if="hasMoreQuestions">
                    <el-button plain @click="loadMoreQuestions">加载更多</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="用户" name="users">
            <div class="tab-content">
              <!-- 用户搜索结果 -->
              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>
              
              <div v-else-if="userResults.length === 0" class="empty-results">
                <el-empty 
                  description="未找到相关用户" 
                  :image-size="200"
                >
                  <template #description>
                    <p>未找到与"{{ keyword }}"相关的用户</p>
                  </template>
                </el-empty>
              </div>
              
              <div v-else class="search-results">
                <div class="result-summary">
                  找到 {{ userTotal }} 个与"{{ keyword }}"相关的用户
                </div>
                
                <div class="user-list">
                  <div
                    v-for="user in userResults"
                    :key="user.id"
                    class="user-card"
                    @click="viewUserProfile(user.id)"
                  >
                    <el-avatar :size="64" :src="user.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"></el-avatar>
                    <div class="user-info">
                      <div class="user-name-row">
                        <h3 class="username" v-html="highlightKeyword(user.username)"></h3>
                        <div class="nickname" v-if="user.nickname">{{ user.nickname }}</div>
                      </div>
                      <p class="user-bio" v-if="user.bio" v-html="highlightKeyword(user.bio)"></p>
                      <div class="user-stats">
                        <span>{{ user.followerCount || 0 }} 粉丝</span>
                      </div>
                    </div>
                    <div class="user-actions">
                      <el-button 
                        :type="user.isFollowing ? 'default' : 'primary'"
                        size="small"
                        @click.stop="isLogin ? handleFollow(user.id, user.isFollowing) : router.push('/login')"
                      >
                        {{ user.isFollowing ? '已关注' : '关注' }}
                      </el-button>
                    </div>
                  </div>
                  
                  <!-- 加载更多 -->
                  <div class="load-more-container" v-if="hasMoreUsers">
                    <el-button plain @click="loadMoreUsers">加载更多</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 添加AI回答标签页 -->
          <el-tab-pane label="AI回答" name="ai">
            <div class="tab-content">
              <!-- AI搜索结果 -->
              <div v-if="aiLoading" class="loading-container">
                <el-skeleton :rows="5" animated />
              </div>
              
              <div v-else-if="!keyword" class="empty-results">
                <el-empty description="请输入搜索关键词获取AI回答" :image-size="200">
                  <template #description>
                    <p>输入问题或关键词，获取DeepSeek AI的智能回答</p>
                  </template>
                </el-empty>
              </div>
              
              <div v-else-if="aiResults.length === 0" class="empty-results">
                <el-empty description="暂无AI回答结果" :image-size="200">
                  <template #description>
                    <p>AI未能针对"{{ keyword }}"提供回答</p>
                    <p>您可以尝试其他关键词或更具体的问题</p>
                  </template>
                  <el-button type="primary" @click="searchAI">重新搜索</el-button>
                </el-empty>
              </div>
              
              <div v-else class="search-results">
                <div class="result-summary">
                  <span>DeepSeek AI 针对"{{ keyword }}"的回答</span>
                  <el-tooltip content="使用DeepSeek大语言模型生成的回答，仅供参考">
                    <el-icon class="info-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
                
                <div class="ai-results">
                  <div v-for="(result, index) in aiResults" :key="index" class="ai-card">
                    <h3 class="ai-title">{{ result.title }}</h3>
                    <div class="ai-content">
                      <p>{{ result.content }}</p>
                    </div>
                    <div class="ai-card-footer">
                      <div class="ai-actions">
                        <el-button type="primary" size="small" @click="copyContent(result.content)">
                          <el-icon><CopyDocument /></el-icon>
                          <span>复制</span>
                        </el-button>
                        <el-button type="info" plain size="small" @click="shareContent(result)">
                          <el-icon><Share /></el-icon>
                          <span>分享</span>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 显示相关问题建议 -->
                <div v-if="similarQuestions.length > 0" class="similar-questions">
                  <h3 class="section-title">相关问题</h3>
                  <div class="similar-list">
                    <div 
                      v-for="(question, index) in similarQuestions" 
                      :key="index"
                      class="similar-item"
                      @click="selectSuggestion(question)"
                    >
                      {{ question }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowLeft, ChatLineSquare, CaretTop, CaretBottom, Star, Setting, InfoFilled, QuestionFilled, CopyDocument, Share } from '@element-plus/icons-vue';
import { useUserStore } from '../stores/user';
import { 
  searchQuestions, 
  searchUsers, 
  saveSearchHistory, 
  searchAll, 
  searchRelatedTags, 
  getSearchSuggestions,
  advancedSearch,
  aiSearchQuestions,
  getSimilarQuestions
} from '../api/search';
import { collectQuestion, cancelCollect, checkQuestionCollected } from '../api/collection';
import { voteAnswer, cancelVote, checkVoteStatus } from '../api/vote';
import SearchBar from '../components/SearchBar.vue';
import AdvancedSearchForm from '../components/AdvancedSearchForm.vue';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 获取用户登录状态
const isLogin = computed(() => userStore.isLogin);

// 搜索相关状态
const keyword = ref('');
const activeTab = ref('questions');
const loading = ref(false);

// 分页数据
const page = ref(1);
const pageSize = ref(10);

// 问题搜索结果
const questionResults = ref([]);
const questionTotal = ref(0);
const hasMoreQuestions = ref(false);

// 用户搜索结果
const userResults = ref([]);
const userTotal = ref(0);
const hasMoreUsers = ref(false);

// AI搜索相关状态
const aiResults = ref([]);
const aiLoading = ref(false);
const similarQuestions = ref([]);

// 相关标签和搜索建议
const relatedTags = ref([]);
const searchSuggestions = ref([]);
const tagUsageCounts = ref({});

// 添加高级搜索相关状态
const showAdvancedSearch = ref(false);
const advancedSearchForm = ref({
  tags: [],
  dateRange: [],
  minViews: undefined,
  minAnswers: undefined,
  sort: 1
});
const hotTags = ref(['javascript', 'java', 'python', 'vue', 'react', 'spring', '前端', '后端', '数据库', '算法']);

// 简易排序（用于非高级搜索模式）
const simpleSort = ref(1);

// 重置搜索
const resetSearch = () => {
  page.value = 1;
  questionResults.value = [];
  userResults.value = [];
  relatedTags.value = [];
  searchSuggestions.value = [];
};

// 使用备用演示数据
const useFallbackDemoData = () => {
  questionResults.value = [
    {
      id: 1,
      title: `搜索结果: ${keyword.value} 问题1`,
      content: `这是包含关键词 "${keyword.value}" 的问题内容，用于演示搜索结果...`,
      createTime: new Date().toISOString(),
      user: { id: 1, username: '测试用户', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
      viewCount: 123,
      answerCount: 5,
      voteCount: 10,
      tags: 'javascript,vue,前端'
    },
    {
      id: 2,
      title: `搜索结果: ${keyword.value} 问题2`,
      content: `另一个包含 "${keyword.value}" this is a demo result...`,
      createTime: new Date(Date.now() - 86400000).toISOString(),
      user: { id: 2, username: '另一用户', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
      viewCount: 89,
      answerCount: 3,
      voteCount: 7,
      tags: 'java,spring,后端'
    }
  ];
  questionTotal.value = questionResults.value.length;
  hasMoreQuestions.value = false;
};

// 获取问题列表后检查投票和收藏状态
const checkUserInteractions = async (questions) => {
  if (!isLogin.value || !questions || questions.length === 0) return;

  try {
    // 获取问题收藏状态
    for (const question of questions) {
      try {
        // 检查收藏状态
        const collectRes = await checkQuestionCollected(question.id);
        if (collectRes && collectRes.data !== undefined) {
          question.isBookmarked = collectRes.data;
          question.is_bookmarked = collectRes.data;
        }

        // 检查投票状态
        const voteRes = await checkVoteStatus(question.id);
        if (voteRes && voteRes.data !== undefined) {
          question.voteStatus = voteRes.data;
        }
      } catch (err) {
        console.error(`检查问题 ${question.id} 互动状态失败:`, err);
      }
    }
  } catch (error) {
    console.error('检查用户互动状态失败:', error);
  }
};

// 尝试使用综合搜索
const trySearchAll = async () => {
  if (!keyword.value.trim()) return;
  
  try {
    loading.value = true;
    
    // 检查是否使用本地数据
    const useLocalData = route.query.local === 'true';
    
    if (useLocalData) {
      console.log('使用本地演示数据进行搜索');
      useFallbackDemoData();
      
      // 模拟相关标签
      relatedTags.value = ['javascript', 'vue', '前端', '后端', 'java'];
      
      // 模拟搜索建议
      searchSuggestions.value = [
        `${keyword.value}相关问题`,
        `如何学习${keyword.value}`,
        `${keyword.value}框架对比`
      ];
      
      loading.value = false;
      return;
    }
    
    // 保存搜索历史（如果已登录）
    if (isLogin.value) {
      await saveSearchHistory(keyword.value);
    }
    
    // 使用综合搜索API
    const res = await searchAll({
      keyword: keyword.value,
      current: page.value,
      size: pageSize.value
    });
    
    console.log('综合搜索结果:', res);
    
    if (res.code === 200 && res.data) {
      // 处理问题结果
      if (res.data.questions && res.data.questions.records) {
        questionResults.value = res.data.questions.records;
        questionTotal.value = res.data.questions.total;
        hasMoreQuestions.value = questionResults.value.length < questionTotal.value;
        
        // 检查收藏和投票状态
        await checkUserInteractions(questionResults.value);
      }
      
      // 处理用户结果
      if (res.data.users && res.data.users.records) {
        userResults.value = res.data.users.records;
        userTotal.value = res.data.users.total;
        hasMoreUsers.value = userResults.value.length < userTotal.value;
      }
      
      // 处理相关标签
      if (res.data.tags) {
        relatedTags.value = res.data.tags;
        
        // 初始化标签使用计数
        if (res.data.tags && res.data.tags.counts) {
          tagUsageCounts.value = res.data.tags.counts;
        } else {
          // 如果后端未提供使用计数，设置默认值
          const defaultCounts = {};
          res.data.tags.forEach((tag, index) => {
            // 生成递减的模拟使用计数
            defaultCounts[tag] = Math.max(10, 30 - index * 5);
          });
          tagUsageCounts.value = defaultCounts;
        }
      }
      
      // 处理搜索建议
      if (res.data.suggestions) {
        searchSuggestions.value = res.data.suggestions;
      }
    } else {
      // 如果综合搜索API出错，回退到单独搜索
      await searchQuestionsData();
      
      // 额外获取相关标签
      try {
        const tagsRes = await searchRelatedTags(keyword.value, 5);
        if (tagsRes.code === 200 && Array.isArray(tagsRes.data)) {
          relatedTags.value = tagsRes.data;
          
          // 初始化标签使用计数
          if (tagsRes.data && tagsRes.data.counts) {
            tagUsageCounts.value = tagsRes.data.counts;
          } else {
            // 如果后端未提供使用计数，设置默认值
            const defaultCounts = {};
            tagsRes.data.forEach((tag, index) => {
              // 生成递减的模拟使用计数
              defaultCounts[tag] = Math.max(10, 30 - index * 5);
            });
            tagUsageCounts.value = defaultCounts;
          }
        }
      } catch (err) {
        console.error('获取相关标签失败:', err);
      }
      
      // 额外获取搜索建议
      try {
        const suggestRes = await getSearchSuggestions(keyword.value, 5);
        if (suggestRes.code === 200 && Array.isArray(suggestRes.data)) {
          searchSuggestions.value = suggestRes.data;
        }
      } catch (err) {
        console.error('获取搜索建议失败:', err);
      }
    }
  } catch (error) {
    console.error('综合搜索失败:', error);
    ElMessage.error('搜索失败，使用演示数据');
    
    // 使用备用演示数据
    useFallbackDemoData();
  } finally {
    loading.value = false;
  }
};

// 执行高级搜索
const doAdvancedSearch = async () => {
  if (!keyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }
  
  try {
    loading.value = true;
    page.value = 1;
    
    // 转换日期范围
    const startDate = advancedSearchForm.value.dateRange && advancedSearchForm.value.dateRange[0] || null;
    const endDate = advancedSearchForm.value.dateRange && advancedSearchForm.value.dateRange[1] || null;
    
    // 转换标签数组为逗号分隔的字符串
    const tags = advancedSearchForm.value.tags.join(',');
    
    // 调用高级搜索API
    const res = await advancedSearch({
      keyword: keyword.value,
      tags: tags,
      startDate: startDate,
      endDate: endDate,
      minViews: advancedSearchForm.value.minViews,
      minAnswers: advancedSearchForm.value.minAnswers,
      current: page.value,
      size: pageSize.value,
      sort: advancedSearchForm.value.sort
    });
    
    console.log('高级搜索结果:', res);
    
    if (res.code === 200 && res.data) {
      activeTab.value = 'questions'; // 切换到问题标签页
      
      // 处理搜索结果
      questionResults.value = res.data.records || [];
      questionTotal.value = res.data.total || 0;
      hasMoreQuestions.value = questionResults.value.length < questionTotal.value;
      
      // 保存搜索历史（如果已登录）
      if (isLogin.value) {
        await saveSearchHistory(keyword.value);
      }
    }
  } catch (error) {
    console.error('高级搜索失败:', error);
    ElMessage.error('高级搜索失败');
  } finally {
    loading.value = false;
  }
};

// 重置高级搜索表单
const resetAdvancedSearch = () => {
  advancedSearchForm.value = {
    tags: [],
    dateRange: [],
    minViews: undefined,
    minAnswers: undefined,
    sort: 1
  };
};

// 处理简易排序变化
const handleSimpleSortChange = () => {
  // 如果关键词为空，不执行搜索
  if (!keyword.value.trim()) return;
  
  // 使用新的排序方式重新搜索
  page.value = 1;
  searchQuestionsData(simpleSort.value);
};

// 更新搜索问题数据方法，增加排序参数
const searchQuestionsData = async (sortValue = simpleSort.value) => {
  if (!keyword.value.trim()) return;
  
  try {
    loading.value = true;
    
    // 检查是否使用本地数据
    const useLocalData = route.query.local === 'true';
    
    if (useLocalData) {
      console.log('使用本地演示数据进行搜索');
      // 从localStorage获取演示数据...
      // ... 原有代码 ...
      loading.value = false;
      return;
    }
    
    // 保存搜索历史（如果已登录）
    if (isLogin.value) {
      await saveSearchHistory(keyword.value);
    }
    
    // 使用排序参数调用API
    const res = await searchQuestions({
      keyword: keyword.value,
      current: page.value,
      size: pageSize.value,
      sort: sortValue
    });
    
    console.log('搜索问题结果:', res);
    
    if (res.code === 200 && res.data && (res.data.records || Array.isArray(res.data))) {
      if (page.value === 1) {
        questionResults.value = res.data.records || res.data;
      } else {
        questionResults.value = [...questionResults.value, ...(res.data.records || res.data)];
      }
      
      questionTotal.value = res.data.total || questionResults.value.length;
      hasMoreQuestions.value = questionResults.value.length < questionTotal.value;
      
      // 检查收藏和投票状态
      await checkUserInteractions(questionResults.value);
    } else {
      // 没有数据或返回格式不对
      questionResults.value = [];
      questionTotal.value = 0;
      hasMoreQuestions.value = false;
      console.warn('搜索问题返回数据格式不正确:', res);
    }
  } catch (error) {
    console.error('搜索问题失败:', error);
    ElMessage.error('搜索问题失败，使用演示数据');
    
    // 使用备用演示数据
    useFallbackDemoData();
  } finally {
    loading.value = false;
  }
};

// 修改加载更多问题方法，传递排序参数
const loadMoreQuestions = () => {
  page.value++;
  searchQuestionsData(simpleSort.value);
};

// 选择搜索建议
const selectSuggestion = (suggestion) => {
  keyword.value = suggestion;
  resetSearch();
  
  // 根据当前标签页执行不同搜索
  if (activeTab.value === 'ai') {
    searchAI();
  } else {
    trySearchAll();
  }
  
  // 更新路由参数，但不触发新的导航
  router.replace({
    path: '/search',
    query: { 
      ...route.query,
      keyword: suggestion
    }
  }).catch(err => console.error('更新路由参数失败:', err));
};

// 选择相关标签
const selectRelatedTag = (tag) => {
  // 将标签添加到搜索关键词
  keyword.value = tag;
  resetSearch();
  trySearchAll();
  
  // 更新路由参数，但不触发新的导航
  router.replace({
    path: '/search',
    query: { 
      ...route.query,
      keyword: tag
    }
  }).catch(err => console.error('更新路由参数失败:', err));
};

// 处理标签页切换
const handleTabChange = (tab) => {
  console.log('切换到标签页:', tab.props.name);
  
  // 切换标签后重置页码
  page.value = 1;
  
  // 如果切换到AI标签，执行AI搜索
  if (tab.props.name === 'ai' && keyword.value && aiResults.value.length === 0) {
    searchAI();
  }
};

// 加载更多用户
const loadMoreUsers = () => {
  page.value++;
  searchUsersData();
};

// 查看问题详情
const viewQuestionDetail = (id) => {
  router.push(`/questions/${id}`);
};

// 查看用户主页
const viewUserProfile = (id) => {
  router.push(`/user/${id}`);
};

// 高亮关键词
const highlightKeyword = (text) => {
  if (!text || !keyword.value) return text || '';
  
  // 转义正则特殊字符，避免XSS风险
  const escapeRegExp = (string) => {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  };
  
  // 处理HTML实体编码，避免XSS
  const escapeHtml = (unsafe) => {
    return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  };
  
  try {
    // 处理文本中可能已有的HTML标签
    const safeText = typeof text === 'string' ? escapeHtml(text) : '';
    
    // 分割关键词并按长度排序，优先匹配长词组
    const keywords = keyword.value.split(/\s+/)
      .filter(k => k.trim())
      .sort((a, b) => b.length - a.length);
    
    // 如果没有有效关键词，直接返回处理后的文本
    if (keywords.length === 0) return safeText;
    
    // 处理多个关键词的高亮，优先匹配完整关键词组合
    let result = safeText;
    
    // 先尝试匹配完整的关键词组合
    if (keywords.length > 1) {
      const fullKeyword = keyword.value.trim();
      const fullSafeKeyword = escapeRegExp(fullKeyword);
      const fullReg = new RegExp(fullSafeKeyword, 'gi');
      result = result.replace(fullReg, (match) => 
        `<span class="highlight highlight-full">${match}</span>`);
    }
    
    // 然后匹配单个关键词
    for (const word of keywords) {
      if (word.trim()) {
        const safeKeyword = escapeRegExp(word.trim());
        const reg = new RegExp(`\\b${safeKeyword}\\b|${safeKeyword}`, 'gi');
        
        // 确保不会处理已高亮的内容
        result = result.replace(
          reg, 
          (match, offset, string) => {
            // 检查是否已经在span标签内
            const prevChars = string.substring(Math.max(0, offset - 50), offset);
            if (prevChars.lastIndexOf('<span class="highlight') > prevChars.lastIndexOf('</span>')) {
              return match; // 已在高亮span中，不重复处理
            }
            return `<span class="highlight">${match}</span>`;
          }
        );
      }
    }
    
    return result;
  } catch (error) {
    console.error('高亮处理失败:', error);
    return text || '';
  }
};

// 获取问题标签
const getQuestionTags = (question) => {
  if (!question.tags) return [];
  
  // 处理不同格式的标签
  if (Array.isArray(question.tags)) {
    return question.tags;
  }
  
  // 如果是字符串，按逗号分隔
  return question.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  try {
    const now = new Date();
    const date = new Date(timestamp);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return timestamp; // 如果无效，直接返回原始值
    }
    
    const diff = Math.floor((now - date) / 1000); // 时间差（秒）
    
    if (diff < 60) {
      return `${diff}秒前`;
    } else if (diff < 3600) {
      return `${Math.floor(diff / 60)}分钟前`;
    } else if (diff < 86400) {
      return `${Math.floor(diff / 3600)}小时前`;
    } else if (diff < 604800) {
      return `${Math.floor(diff / 86400)}天前`;
    } else {
      // 格式化日期
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
  } catch (error) {
    console.error('时间格式化失败:', error);
    return timestamp || '';
  }
};

// 处理收藏问题
const handleBookmark = async (id) => {
  try {
    const question = questionResults.value.find(item => item.id === id);
    if (!question) return;
    
    // 先更新UI状态提供即时反馈
    const wasBookmarked = question.isBookmarked || question.is_bookmarked;
    question.isBookmarked = !wasBookmarked;
    question.is_bookmarked = !wasBookmarked;
    
    if (wasBookmarked) {
      await cancelCollect(id);
      ElMessage.success('已取消收藏');
    } else {
      await collectQuestion(id);
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    // 如果操作失败，恢复原来的状态
    const question = questionResults.value.find(item => item.id === id);
    if (question) {
      question.isBookmarked = !question.isBookmarked;
      question.is_bookmarked = !question.is_bookmarked;
    }
    console.error('操作收藏失败:', error);
    ElMessage.error('操作收藏失败，请稍后再试');
  }
};

// 处理投票问题
const handleVote = async (id, type) => {
  try {
    const question = questionResults.value.find(item => item.id === id);
    if (!question) return;
    
    // 记录原来的状态
    const oldVoteStatus = question.voteStatus || 0;
    const oldVoteCount = question.voteCount || question.votes_count || 0;
    
    // 更新UI状态提供即时反馈
    if (type === 'up') {
      // 如果已经赞过，则取消赞
      if (oldVoteStatus === 1) {
        question.voteStatus = 0;
        question.voteCount = Math.max(0, oldVoteCount - 1);
        question.votes_count = Math.max(0, oldVoteCount - 1);
        await cancelVote(id);
        ElMessage.success('已取消点赞');
      } else {
        // 如果没赞过或者是踩，改为赞
        question.voteStatus = 1;
        // 如果之前是踩，则+2（-1变+1）
        const addValue = oldVoteStatus === 2 ? 2 : 1;
        question.voteCount = oldVoteCount + addValue;
        question.votes_count = oldVoteCount + addValue;
        await voteAnswer({
          answerId: id,
          voteType: 1 // 1表示赞成
        });
        ElMessage.success('点赞成功');
      }
    } else if (type === 'down') {
      // 如果已经踩过，则取消踩
      if (oldVoteStatus === 2) {
        question.voteStatus = 0;
        question.voteCount = oldVoteCount;
        question.votes_count = oldVoteCount;
        await cancelVote(id);
        ElMessage.success('已取消踩');
      } else {
        // 如果没踩过或者是赞，改为踩
        question.voteStatus = 2;
        // 如果之前是赞，则-2（+1变-1）
        const subValue = oldVoteStatus === 1 ? 2 : 0;
        question.voteCount = Math.max(0, oldVoteCount - subValue);
        question.votes_count = Math.max(0, oldVoteCount - subValue);
        await voteAnswer({
          answerId: id,
          voteType: 2 // 2表示反对
        });
        ElMessage.success('已踩');
      }
    }
  } catch (error) {
    // 如果操作失败，恢复原来的UI状态
    console.error('投票操作失败:', error);
    ElMessage.error('投票操作失败，请稍后再试');
    
    // 重新加载数据或者直接重置该问题状态
    try {
      await trySearchAll();
    } catch (err) {
      console.error('重新加载数据失败:', err);
    }
  }
};

// 处理关注用户
const handleFollow = async (id, isFollowing) => {
  try {
    const user = userResults.value.find(item => item.id === id);
    if (!user) return;
    
    // 这里使用mockup实现关注功能
    if (isFollowing) {
      // 取消关注
      user.isFollowing = false;
      user.followerCount = Math.max(0, user.followerCount - 1);
      ElMessage.success('已取消关注');
    } else {
      // 关注
      user.isFollowing = true;
      user.followerCount = (user.followerCount || 0) + 1;
      ElMessage.success('关注成功');
    }
  } catch (error) {
    console.error('关注操作失败:', error);
    ElMessage.error('关注操作失败');
  }
};

// 处理搜索事件
const handleSearchEvent = (event) => {
  const newKeyword = event.detail.keyword;
  const useLocalData = event.detail.useLocalData || false;
  
  console.log('接收到搜索关键词更新:', newKeyword, '使用本地数据:', useLocalData);
  
  if (newKeyword) {
    keyword.value = newKeyword;
    
    // 更新路由参数，但不触发新的导航
    router.replace({
      path: '/search',
      query: { 
        ...route.query,
        keyword: newKeyword,
        local: useLocalData ? 'true' : undefined
      }
    }).catch(err => console.error('更新路由参数失败:', err));
    
    resetSearch();
    if (activeTab.value === 'questions') {
      searchQuestionsData();
    } else {
      searchUsersData();
    }
  }
};

// 监听路由参数变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    keyword.value = newKeyword;
    resetSearch();
    if (activeTab.value === 'questions') {
      searchQuestionsData();
    } else {
      searchUsersData();
    }
  }
}, { immediate: true });

// 监听标签页切换
watch(() => activeTab.value, (newTab) => {
  if (newTab === 'questions' && questionResults.value.length === 0) {
    page.value = 1;
    searchQuestionsData();
  } else if (newTab === 'users' && userResults.value.length === 0) {
    page.value = 1;
    searchUsersData();
  } else if (newTab === 'ai' && keyword.value && aiResults.value.length === 0) {
    searchAI();
  }
});

// 在SearchPage.vue中添加onMounted钩子以在页面加载时检查关键词并执行搜索
onMounted(() => {
  console.log('SearchPage加载，当前关键词:', keyword.value);
  console.log('路由参数:', route.query);
  
  if (route.query.keyword) {
    keyword.value = route.query.keyword;
    // 使用综合搜索
    trySearchAll();
  }
  
  // 监听自定义搜索事件（当在搜索页面上再次搜索时）
  window.addEventListener('search-keyword-changed', handleSearchEvent);
});

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('search-keyword-changed', handleSearchEvent);
});

// 打开搜索指南
const openSearchTips = () => {
  // 使用窗口打开搜索指南
  window.open('/search-tips.md', '_blank');
  
  // 或者使用对话框显示搜索指南（需要实现）
  // ElMessageBox.alert('搜索指南内容', '搜索使用指南', {
  //   dangerouslyUseHTMLString: true,
  //   closeOnClickModal: true
  // });
};

// 搜索AI回答
const searchAI = async () => {
  if (!keyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }
  
  try {
    aiLoading.value = true;
    
    // 调用AI搜索接口
    const res = await aiSearchQuestions({
      query: keyword.value,
      limit: 5
    });
    
    console.log('AI搜索结果:', res);
    
    if (res.code === 200 && res.data) {
      aiResults.value = res.data;
      
      // 获取相关问题建议
      try {
        const similarRes = await getSimilarQuestions(keyword.value, 5);
        if (similarRes.code === 200 && Array.isArray(similarRes.data)) {
          similarQuestions.value = similarRes.data;
        }
      } catch (err) {
        console.error('获取相似问题失败:', err);
      }
    } else {
      aiResults.value = [];
      ElMessage.warning('AI搜索返回数据格式不正确');
    }
  } catch (error) {
    console.error('AI搜索失败:', error);
    ElMessage.error('AI搜索失败');
    aiResults.value = [];
  } finally {
    aiLoading.value = false;
  }
};

// 复制内容
const copyContent = (content) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(content)
      .then(() => {
        ElMessage.success('复制成功');
      })
      .catch(() => {
        ElMessage.error('复制失败，请手动复制');
      });
  } else {
    // 兼容方案
    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    ElMessage.success('复制成功');
  }
};

// 分享内容
const shareContent = (result) => {
  try {
    if (navigator.share) {
      navigator.share({
        title: result.title,
        text: result.content,
        url: window.location.href
      });
    } else {
      ElMessage.info('您的浏览器不支持分享功能，请手动复制分享');
      copyContent(result.content);
    }
  } catch (error) {
    console.error('分享失败:', error);
    ElMessage.error('分享失败');
  }
};
</script>

<style scoped>
.search-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  margin-bottom: 20px;
}

.search-top {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 16px;
  color: #606266;
}

.back-button:hover {
  color: #409EFF;
}

.search-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.search-bar-container {
  width: 100%;
}

.search-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-tabs {
  padding: 16px;
}

.tab-content {
  padding-top: 16px;
}

.loading-container {
  padding: 20px 0;
}

.empty-results {
  padding: 40px 0;
  text-align: center;
}

.result-summary {
  margin-bottom: 16px;
  color: #606266;
  font-size: 14px;
}

/* 问题列表样式 */
.question-list {
  margin-top: 16px;
}

.question-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.question-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  margin-left: 12px;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.publish-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.question-content {
  margin-bottom: 16px;
}

.question-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px;
}

.question-preview {
  font-size: 14px;
  color: #606266;
  margin: 0 0 12px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.tag-item {
  font-size: 12px;
}

.question-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.interaction-area {
  display: flex;
  align-items: center;
  gap: 16px;
}

.vote-area {
  display: flex;
  align-items: center;
}

.vote-btn {
  padding: 4px;
  transition: all 0.3s ease;
}

.active-vote, .active-vote-down {
  transform: scale(1.2);
  transition: transform 0.3s ease;
}

.active-vote {
  color: #409EFF !important;
}

.active-vote-down {
  color: #F56C6C !important;
}

.vote-count {
  margin: 0 4px;
  font-size: 14px;
  color: #606266;
  min-width: 20px;
  text-align: center;
}

.voted-up {
  color: #409EFF;
  font-weight: 600;
}

.voted-down {
  color: #F56C6C;
  font-weight: 600;
}

.answer-count {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  font-size: 14px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-btn.is-collected {
  color: #E6A23C;
}

.action-btn .active-icon {
  color: #E6A23C;
  animation: pulse 0.3s ease-in-out;
}

.action-btn .active-text {
  color: #E6A23C;
  font-weight: 500;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 用户列表样式 */
.user-list {
  margin-top: 16px;
}

.user-card {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.user-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
  flex: 1;
  margin-left: 16px;
}

.user-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.user-name-row .username {
  font-size: 16px;
  margin: 0;
}

.nickname {
  color: #909399;
  font-size: 14px;
}

.user-bio {
  font-size: 14px;
  color: #606266;
  margin: 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.user-stats {
  font-size: 12px;
  color: #909399;
}

.user-actions {
  margin-left: 16px;
}

.load-more-container {
  text-align: center;
  margin: 20px 0;
}

/* 高亮样式 */
:deep(.highlight) {
  color: #409EFF;
  font-weight: 500;
  background-color: rgba(64, 158, 255, 0.1);
}

/* 添加搜索建议和相关标签样式 */
.search-meta {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
  margin-bottom: 20px;
}

.suggestions-title, .tags-title {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 12px;
}

.suggestions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 16px;
}

.suggestion-item {
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
  background-color: #ecf5ff;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #d9ecff;
  text-decoration: underline;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
}

.tag-item:hover {
  background-color: #e8f4ff;
}

/* 添加高级搜索样式 */
.advanced-search {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
  margin-bottom: 20px;
}

.advanced-search-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px;
}

.search-operations {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  align-items: center;
  padding: 0 16px;
}

.tags-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* AI回答卡片样式 */
.ai-results {
  margin-top: 16px;
}

.ai-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #409EFF;
}

.ai-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px;
}

.ai-content {
  font-size: 15px;
  color: #303133;
  line-height: 1.6;
  margin-bottom: 20px;
  white-space: pre-line;
}

.ai-card-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.ai-actions {
  display: flex;
  gap: 12px;
}

.info-icon {
  margin-left: 8px;
  color: #909399;
  cursor: help;
}

/* 相似问题样式 */
.similar-questions {
  margin-top: 24px;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 12px;
}

.similar-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.similar-item {
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #ecf5ff;
  transition: background-color 0.2s;
}

.similar-item:hover {
  background-color: #d9ecff;
  text-decoration: underline;
}
</style> 